﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Google.GData.Calendar;
using System.Globalization;
using System.ComponentModel;
using Google.GData.Client;

namespace Journal.Helpers
{
    /// <summary>
    /// Interaction logic for GoogleLogin.xaml
    /// </summary>
    public partial class GoogleLogin : Window
    {
        private CalendarFeed result;
        private BackgroundWorker worker;
        private CalendarService service = GoogleServices.Instance.CalendarService;

        public GoogleLogin()
        {
            InitializeComponent();
            this.textBoxUsername.Focus();
            
            // Initialize worker
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar.IsIndeterminate = true;
            this.progressBar.Visibility = Visibility.Visible;
            this.buttonOK.IsEnabled = false;
            this.buttonCancel.IsEnabled = false;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (result == null)
            {
                this.progressBar.IsIndeterminate = false;
                this.progressBar.Visibility = Visibility.Hidden;
                this.buttonOK.IsEnabled = true;
                this.buttonCancel.IsEnabled = true;
                this.textBoxUsername.Focus();
            }
            else
            {
                this.Close();
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Send progress change
            BackgroundWorker worker = (BackgroundWorker)sender;
            worker.ReportProgress(42); // :)
            // Try to get google service
            UserCredentials uc = (UserCredentials)e.Argument;
            service.setUserCredentials(uc.username, uc.password);

            try
            {
                result = GoogleServices.Instance.RetrieveUserCalendars();
            }
            catch (GDataRequestException ex)
            {
                if (ex.ResponseString != null && ex.ResponseString.Contains("Error=BadAuthentication"))
                {
                    MessageBoxHelper.ShowAuthenticationErrorMessage();
                }
                else if (ex.ResponseString == null && ex.InnerException.Message.Contains("'www.google.com'"))
                {
                    MessageBoxHelper.ShowConnectionErrorMessage();
                }
            }
            catch (Exception)
            {
                MessageBoxHelper.ShowCriticalErrorMessage();
                this.Close();
            }
        }

        /// <summary>
        /// Invokes standard ShowDialog() method and returns calendars
        /// from user's google account.
        /// </summary>
        /// <returns>CalendarFeed</returns>
        public CalendarFeed ShowLoginAndRetrieveCalendarFeed()
        {
            this.ShowDialog();
            return result;
        }

        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            worker.RunWorkerAsync(new UserCredentials(this.textBoxUsername.Text, this.passwordBox.Password));
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            service.Credentials = null;
            this.Close();
        }

        /// <summary>
        /// Helper class used to pass username and password to local background worker
        /// </summary>
        private class UserCredentials
        {
            public string username { get; set; }
            public string password { get; set; }

            public UserCredentials(string username, string password)
            {
                this.username = username;
                this.password = password;
            }
        }
    }
}
